﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;

namespace RBAC.Web.Utilities
{
    // ยังไม่ใช้งานไม่ต้องทำ T4 ครับ
    // Example
    // var listDisplay = Utilities.ResultMessageMapper.Mapping(new ListEmployeeModel(), output, Utilities.MessageUtil.GetMessage(Operation.Edit, output.Status));
    public class ResultMessageMapper
    {
        public static TListModel Mapping<TListModel, TResponse>(TListModel tList, TResponse tRes, string message)
        {
            Type tListType = tList.GetType();
            PropertyInfo propList = tListType.GetProperty("ListItems");
            PropertyInfo propIsSuccess = tListType.GetProperty("IsSuccess");
            PropertyInfo propMessage = tListType.GetProperty("Message");
            try
            {
                if (propList == null || propIsSuccess == null || propMessage == null)
                    throw new ProperityNotFoundException();

                if (tRes != null)
                {
                    Type tResType = tRes.GetType();
                    PropertyInfo propData = tResType.GetProperty("Data");
                    PropertyInfo propStatus = tResType.GetProperty("Status");

                    if (propData == null || propStatus == null)
                        throw new ProperityNotFoundException();

                    bool? status = propStatus.GetValue(tRes, null) as bool?;

                    if (status.Value)
                    {
                        propIsSuccess.SetValue(tList, true, null);
                        IList a = propList.GetValue(tList, null) as IList;
                        a.Add(propData.GetValue(tRes, null));

                        propList.SetValue(tList, a, null);
                    }
                    else
                    {
                        propIsSuccess.SetValue(tList, false, null);
                    }

                    propMessage.SetValue(tList, message, null);

                }

                return tList;
            }
            catch (ProperityNotFoundException)
            {
                return tList;
            }
            catch (Exception)
            {
                propIsSuccess.SetValue(tList, false, null);
                propMessage.SetValue(tList, "System Error", null);
                return tList;
            }
        }
    }

    class ProperityNotFoundException : Exception
    {
        public ProperityNotFoundException() : base() { }
        public ProperityNotFoundException(string message) : base(message) { }
    }
}